package card

import (
	"data/config"
	"data/view"
	"log"
	"public/message"
	"public/mycache"
	"public/myhttp"
	"public/mylog"
	"public/mysqldb"
	"public/tools"
	"public/weixin"
	"strconv"
	"time"

	"github.com/ant0ine/go-json-rest/rest"
)

//查询卡券code
func GetCode(w rest.ResponseWriter, r *rest.Request) {
	var req GetCodeParam
	tools.GetRequestJsonObj(r, &req)

	//入口参数检测
	if !tools.CheckParam(req.Code) {
		w.WriteJson(message.GetErrorMsg(message.ParameterInvalid))
		return
	}
	access_token, err := weixin.GetAccessToken()
	if len(access_token) == 0 || err != nil {
		mylog.Error(err)
		w.WriteJson(message.GetErrorMsg(message.UnknownError))
		return
	}
	req.Check_consume = true
	var result CodeRet
	myhttp.SendPost(req, &result, GETCODEURL+access_token)
	if result.Can_consume { //卡券有效
		var db mysqldb.MySqlDB
		defer db.OnDestoryDB()
		orm := db.OnGetDBOrm(config.GetDbUrl())

		var card view.Card_info_tbl
		card.Code = req.Code
		card.Card_id = result.Card.Card_id
		card.Open_id = result.Openid
		card.Begin_time = result.Card.Begin_time
		card.End_time = result.Card.End_time
		if result.Can_consume {
			card.Can_consume = 1
		}
		orm.Create(&card)
		//先从缓存中获取
		cache := mycache.OnGetCache("wingame_config")
		var tp interface{}
		tp, b := cache.Value("all")
		if b {
			c_info := tp.(map[string]view.Card_config_tbl)
			result.Card.Title = c_info[result.Card.Card_id].Title
			result.Card.Desc = c_info[result.Card.Card_id].Desc
			result.Card.Url = c_info[result.Card.Card_id].Url
		}
	}
	msg := message.GetSuccessMsg()
	msg.Data = result
	w.WriteJson(msg)
}

//核销卡券
func Comsume(w rest.ResponseWriter, r *rest.Request) {
	var req ComsumeParam
	tools.GetRequestJsonObj(r, &req)

	//入口参数检测
	if !tools.CheckParam(req.Code) {
		w.WriteJson(message.GetErrorMsg(message.ParameterInvalid))
		return
	}
	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())

	var card view.Card_info_tbl
	orm.Where("code = ? and can_consume = ?", req.Code, 1).Find(&card)
	if card.Id == 0 {
		w.WriteJson(message.GetErrorMsg(message.NotFindError))
		return
	}
	access_token, err := weixin.GetAccessToken()
	if len(access_token) == 0 || err != nil {
		mylog.Error(err)
		w.WriteJson(message.GetErrorMsg(message.UnknownError))
		return
	}
	var result CodeRet
	myhttp.SendPost(req, &result, CONSUMECODEURL+access_token)
	if result.Errcode == 0 { //核销成功
		orm.Table("card_info_tbl").Where("code = ?", req.Code).Update("is_consume", 1)
	}
	msg := message.GetSuccessMsg()
	msg.Data = result
	w.WriteJson(msg)
}

//获取cardSign签名信息
func GetSign(w rest.ResponseWriter, r *rest.Request) {
	var req GetSignParam
	tools.GetRequestJsonObj(r, &req)

	//入口参数检测
	if len(req.Card_id) == 0 && len(req.Card_type) == 0 {
		w.WriteJson(message.GetErrorMsg(message.ParameterInvalid))
		return
	}
	api_ticket, err := weixin.GetApiTicket()
	if err != nil {
		w.WriteJson(message.GetErrorMsg(message.UnknownError))
		return
	}
	log.Println("ttt", api_ticket)

	nonce_str := tools.GetRandomString(5)
	timestamp := strconv.FormatInt(time.Now().Unix(), 10)
	var sign string
	if len(req.Card_id) > 0 { //添加到卡包
		var str = []string{nonce_str, timestamp, api_ticket, req.Card_id}
		rank_s := tools.DictSort(str)    //按字典排序
		sign = tools.Sha1Encrypt(rank_s) //Sha1加密
	}
	if len(req.Card_type) > 0 { //拉取卡券列表
		var str = []string{nonce_str, timestamp, api_ticket, req.Card_type, config.GetWxInfo().AppID}
		rank_s := tools.DictSort(str)    //按字典排序
		sign = tools.Sha1Encrypt(rank_s) //Sha1加密
	}
	msg := message.GetSuccessMsg(message.NormalMessageId)
	mp := make(map[string]interface{})
	mp["nonce_str"] = nonce_str
	mp["timestamp"] = timestamp
	mp["sign"] = sign
	mp["app_id"] = config.GetWxInfo().AppID
	msg.Data = mp
	w.WriteJson(msg)
}
